package br.com.covosys.util;

import java.io.Serializable;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import br.com.covosys.controller.GenericController;
import br.com.covosys.dao.GenericDAO;
import br.com.covosys.model.GenericModel;

@Component
public class SpringFactory implements BeanFactoryAware {
	
	private static BeanFactory beanFactory;
	
	@SuppressWarnings("unchecked")
	public static <BEAN extends Serializable> GenericModel<BEAN, ? extends GenericDAO<BEAN>> getModel(Class<BEAN> beanClass) {
		String modelName = StringUtils.uncapitalize(beanClass.getSimpleName()+"ModelImpl");
		return beanFactory.getBean(modelName, GenericModel.class);
	}
	
	@SuppressWarnings("unchecked")
	public static <BEAN extends Serializable> GenericDAO<BEAN> getDAO(Class<BEAN> beanClass) {
		String daoName = StringUtils.uncapitalize(beanClass.getSimpleName()+"DAOImpl");
		return beanFactory.getBean(daoName, GenericDAO.class);
	}
	
	@SuppressWarnings("unchecked")
	public static <BEAN extends Serializable> GenericController<BEAN, ? extends GenericModel<BEAN, ? extends GenericDAO<BEAN>>> getController(Class<BEAN> beanClass) {
		String controllerName = StringUtils.uncapitalize(beanClass.getSimpleName()+"Controller");
		return beanFactory.getBean(controllerName, GenericController.class);
	}
	
	public static <BEAN> BEAN getBean(Class<BEAN> klass) {
		return (BEAN) beanFactory.getBean(klass);
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		SpringFactory.beanFactory = beanFactory;
	}
}